package com.dec.flume.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;

public class FlumeHttp {

    public static void main(String[] args) {
        // 创建客户端
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://192.168.10.37:50000");

        post.addHeader("key","PIAC_T00101");
//        post.addHeader("collectTime","1538121460986");
        post.addHeader("Content-Type","binary/octet-stream");
        // 构造请求数据
        String t1= "{\"pltType\":\"T\",\"pltCode\":\"001\",\"setCode\":\"01\"}";
        String t2= "{\"pltType\":\"T\",\"pltCode\":\"001\",\"setCode\":\"02\"}";
        String t3= "{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"01\"}";
        String t4= "{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"02\"}";
        String t5= "[{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"01\"},{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"02\"}]";
        String t6= "[{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"01\"},{\"pltType\":\"T\",\"pltCode\":\"002\",\"setCode\":\"01\"}]";
        ByteArrayEntity entity = new ByteArrayEntity("PIAC_T00101 50000 rrrr接入测试".getBytes());
//        ByteArrayEntity entity = new ByteArrayEntity(gZip(t6.getBytes()));
        post.setEntity(entity);

        // HTTP响应、响应状态码
        CloseableHttpResponse response = null;
        Integer statusCode;
        String responseContent = null;
        try {
            // 执行post请求
            response = client.execute(post);
            statusCode = response.getStatusLine().getStatusCode();

            HttpEntity httpEntity = response.getEntity();
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println(statusCode+","+responseContent);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] gZip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            gzip.close();
            b = bos.toByteArray();
            bos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return b;
    }
}
